package com.abm;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.abm.data.DatabaseManager;
import com.abm.dbclases.Client;
import com.abm.entity.ListaActividad;
import com.abm.adapters.SearchListAdapter;
import com.abm.R;



public class ClientActivity extends ListaActividad {
	public static String PATH_APPDIRs = "sistema_ventas";
	public static Client clientEdit = null;
	
	private ListView listView;
	private List<Client> clientList;
	private List<String> clientListStr;
	private ImageButton btn_add;
	private EditText filter; 
	private ListView m_listview;
	private ArrayList<Client> m_text_sort;
	
	private DatabaseManager manager;
	private Context mContext;
	
	private int m_textlength = 0;
	
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_client);

		m_text_sort = new ArrayList<Client>();
		mContext = getApplicationContext();
		manager = DatabaseManager.getInstance();
		m_listview = (ListView) findViewById(android.R.id.list);
		filter = (EditText) findViewById(R.id.edtFilter);
		listView = (ListView) getListView();
		
		updateList_customAdapter();

		btn_add = (ImageButton) findViewById(R.id.abm_clientadd);
		btn_add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();

				intent.setClass(getApplicationContext(),
						AddClientActivity.class);
				startActivity(intent);

			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				try {
					if (clientList.size() <= 0)
						return;
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		filter.addTextChangedListener(new TextWatcher()
        {

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				m_textlength = filter.getText().length();
                m_text_sort.clear();
//                image_sort.clear();

                
                for (Client item : clientList) {
                	if (m_textlength <= item.getName().length()) {
                		if (filter.getText().toString().equalsIgnoreCase((String) item.getName().subSequence(0, m_textlength)))
                        {
                            m_text_sort.add(item);

                        }
                	}


    			}
                
                m_listview.setAdapter(new CustomAdapter_client_iconrow_custom(ClientActivity.this, m_text_sort));
				
			}
			
        });
		
		

	}

	
	
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateList_customAdapter();
	}
	
	private void updateList_customAdapter() {
		clientList = manager.getAllclient();
		clientListStr = new ArrayList<String>();
		
		if (clientList.size() > 0) {
			for (Client item : clientList) {
				clientListStr.add(item.getName());
				registerForContextMenu(listView);
			}
		} else {
			clientListStr.add(getResources().getString(R.string.no_item_added));
			unregisterForContextMenu(listView);
		}
		clientList = manager.getAllclient();

		CustomAdapter_client_iconrow_custom customAdapter = new CustomAdapter_client_iconrow_custom(
				mContext, clientList);

		listView.setAdapter(customAdapter);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.client, menu);
		return true;
	}

	/**
	 * @param String
	 *            message
	 * @param String
	 *            title
	 * @return
	 */
//	public Dialog showDialogEliminar(String message, String title, final int ID) {
//		//
//
//		customDialog = new Dialog(ClientActivity.this);
//		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		customDialog.setContentView(R.layout.simpledialog_okcancel);
//		customDialog.setCancelable(false);
//
//		TextView tv_title = (TextView) customDialog
//				.findViewById(R.id.simpledialog_okcancel_title);
//		TextView tv_text = (TextView) customDialog
//				.findViewById(R.id.simpledialog_okcancel_text);
//		Button btn_ok = (Button) customDialog
//				.findViewById(R.id.simpledialog_okcancel_ok);
//		Button btn_cancel = (Button) customDialog
//				.findViewById(R.id.simpledialog_okcancel_cancel);
//
//		tv_title.setText(title);
//		tv_text.setText(message);
//
//		btn_ok.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				manager.deleteClientByID(ID);
//				updateList_customAdapter();
//				customDialog.cancel();
//				// finish();
//			}
//		});
//
//		btn_cancel.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				customDialog.cancel();
//				// finish();
//			}
//		});
//		return customDialog;
//	}


	
	public class CustomAdapter_client_iconrow_custom extends BaseAdapter
			implements Filterable {
		/**
		 * 
		 */
		private Context mContext;
		private List<Client> list_client;

		public CustomAdapter_client_iconrow_custom(Context context,
				List<Client> clientList) {
			mContext = context;
			this.list_client = clientList;

		}

		public View getView(final int position, View v, ViewGroup parent) {
			View mView = v;
			if (mView == null) {
				LayoutInflater vi = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				mView = vi.inflate(R.layout.iconrow_custom, null);
			}

			TextView tv_name_surname = (TextView) mView
					.findViewById(R.id.iconrow_custom_tv_title);
			TextView tv_company = (TextView) mView
					.findViewById(R.id.iconrow_custom_tv_desc);

			ImageButton imb_delete = (ImageButton) mView
					.findViewById(R.id.iconrow_custom_imb_delete);
			ImageButton imb_edit = (ImageButton) mView
					.findViewById(R.id.iconrow_custom_imb_edit);
			ImageButton imb_add = (ImageButton) mView
					.findViewById(R.id.iconrow_custom_imagebutton_addproduct);

			imb_add.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					clientEdit = clientList.get(position);

				}
			});

			if (list_client.get(position) != null) {
				tv_name_surname.setTextColor(Color.BLACK);
				tv_name_surname.setText(list_client.get(position).getName() + " " + list_client.get(position).getSurname());

				tv_company.setText(list_client.get(position).getCompany());
				tv_company.setTextColor(Color.BLACK);

			}

			imb_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
			        AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
			        
			        builder.setMessage("Are you sure you want to delete this client?")
			        	   .setTitle("Delete")
			               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {
			                	   	Log.i("Dialogos", "Confirmacion Aceptada.");
			                	   	manager.deleteClientByID(clientList.get(position).getId());
			                	   	updateList_customAdapter();
			       					dialog.cancel();
			                   }
			               })
			               .setNegativeButton("No", new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {
			                	   	Log.i("Dialogos", "Confirmacion Cancelada.");
			       					dialog.cancel();
			                   }
			               });

			        builder.show();
			        
					
				}
			});

			imb_edit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();

					intent.setClass(getApplicationContext(), AddClientActivity.class);

					intent.putExtra("CLIENT_ID", clientList.get(position).getId());
					
					startActivity(intent);
					
				}
			});

			// v.setBackground(mContext.getResources().getDrawable(
			// R.drawable.fondolist));

			return mView;
		}

		
		
		
		
		public int getCount() {
			return list_client.size();
		}

		public Object getItem(int position) {
			return list_client.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		@Override
		public Filter getFilter() {
			return new Filter() {

				@SuppressWarnings("unchecked")
				@Override
				protected void publishResults(CharSequence constraint,
						FilterResults results) {
					list_client = (List<Client>) results.values;
					CustomAdapter_client_iconrow_custom.this
							.notifyDataSetChanged();
				}

				@Override
				protected FilterResults performFiltering(CharSequence constraint) {
					List<Client> filteredResults = getFilteredResults(constraint);
					FilterResults results = new FilterResults();
					results.values = filteredResults;
					return results;
				}
			};
		}

		protected List<Client> getFilteredResults(CharSequence constraint) {
			ArrayList<Client> filteredList = new ArrayList<Client>();
			for (Client c : list_client) {
				if (c.getName().trim().toLowerCase()
						.startsWith(constraint.toString().trim().toLowerCase())) {
					filteredList.add(c);
				}
			}
			return filteredList;
		}

	}

}